module.exports = (app)->
	new Handler app


class Handler
	constructor: (app)->
		@app = app

	enter: (msg, session, next)=>
		rid = msg.rid
		uid = "#{msg.username}*#{rid}"
		sessionService = @app.get 'sessionService'

		# duplicate log in
		if !!sessionService.getByUid uid
			next null, {code: 500,error: true}
			return
		session.bind uid
		session.set 'rid', rid
		await session.push 'rid', defer err
		if err
			console.error "set rid for session service failed! error is #{err.stack}"

		session.on 'closed', onUserLeave.bind(null, @app)
		# put user into channel
		
		await  @app.rpc.chat.chatRemote.add session, uid, @app.get('serverId'), rid, true , defer users
		next null, {users:users}

	
onUserLeave = (app, session)->
	if !session || !session.uid
		return
	app.rpc.chat.chatRemote.kick session, session.uid, app.get('serverId'), session.get('rid'), null
